<template>
  <div class="min-h-screen bg-base-bg p-4 md:p-8">
    <!-- 页面标题 -->
    <div class="mb-8 text-center">
      <h1 class="text-3xl font-bold text-base-text mb-2">Personal Course Management System</h1>
      <p class="text-gray-600">Efficiently manage courses to avoid time conflicts</p>
    </div>
    <!-- 操作栏：添加课程按钮 + 视图切换 -->
    <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mb-6">
      <!-- 添加课程按钮 -->
      <button
        @click="showAddForm = true"
        class="bg-course-selected text-white py-2 px-6 rounded-md hover:bg-course-selected/90 transition-colors"
      >
        <i class="mr-2">+</i> Add course
      </button>
      <!-- 视图切换 -->
      <div class="flex gap-2">
        <button
          @click="currentView = 'list'"
          :class="currentView === 'list' ? 'bg-course-default text-white' : 'bg-gray-200 text-gray-700'"
          class="py-1 px-4 rounded-md transition-colors"
        >
          List view
        </button>
        <button
          @click="currentView = 'calendar'"
          :class="currentView === 'calendar' ? 'bg-course-default text-white' : 'bg-gray-200 text-gray-700'"
          class="py-1 px-4 rounded-md transition-colors"
        >
          Calendar View
        </button>
      </div>
    </div>
    <!-- 课程表单弹窗（添加/编辑） -->
    <div v-if="showAddForm || showEditForm" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <CourseForm
        :is-edit="showEditForm"
        :edit-course="currentEditCourse"
        @submit="handleCourseSubmit"
        @cancel="handleFormCancel"
      />
    </div>
    <!-- 冲突提示弹窗 -->
    <div v-if="showConflictAlert" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <ConflictAlert
        :conflict-course="conflictCourse"
        @confirm="showConflictAlert = false"
      />
    </div>
    <!-- 视图内容区域 -->
    <div class="w-full max-w-6xl mx-auto">
      <!-- 列表视图 -->
      <div v-if="currentView === 'list'">
        <CourseList
          :courses="courses"
          @edit-course="handleEditCourse"
          @delete-course="handleDeleteCourse"
        />
      </div>
      <!-- 日历视图 -->
      <div v-else-if="currentView === 'calendar'">
        <CalendarView
          :courses="courses"
          @course-click="handleEditCourse"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
// 引入组件
import CourseForm from '@/components/CourseForm.vue'
import CourseList from '@/components/CourseList.vue'
import CalendarView from '@/components/CalendarView.vue'
import ConflictAlert from '@/components/ConflictAlert.vue'
// 引入全局配置（若有）
// import { appConfig } from '@/config/appConfig'

// 1. 状态管理：恢复 currentView 定义（控制视图切换）
const currentView = ref('list') // 默认显示列表视图，可根据需求改为 'calendar'
const courses = ref([]) // 课程列表（含 startDate/endDate）
const showAddForm = ref(false) // 显示添加课程表单
const showEditForm = ref(false) // 显示编辑课程表单
const currentEditCourse = ref(null) // 当前编辑的课程（含 startDate/endDate）
const showConflictAlert = ref(false) // 显示冲突提示
const conflictCourse = ref(null) // 冲突的课程信息

// 2. 页面挂载：从本地存储加载课程（含新日期字段）
onMounted(() => {
  const savedCourses = localStorage.getItem('scu_courses')
  console.log('从本地存储读取的数据：', savedCourses); // 新增：读取前打印
  if (savedCourses) {
    let parsedCourses = JSON.parse(savedCourses)
    // 过滤无效数据（确保核心字段存在）
    parsedCourses = parsedCourses.filter(course => 
      course.name && 
      course.teacher && 
      (course.day !== undefined || course.weekday !== undefined) && 
      course.startTime && 
      course.endTime
    )
    // 为旧数据补充唯一 ID
    parsedCourses = parsedCourses.map(course => ({
      id: course.id || Date.now().toString() + Math.random().toString(36).slice(2),
      ...course
    }))
    courses.value = parsedCourses
    console.log('解析后的数据：', courses.value); // 新增：解析后打印
    checkAllCoursesConflict() // 加载后重新检测冲突
  }
  console.log('最终 courses 数据：', courses.value); // 新增：加载后打印
})

// 3. 保存课程到本地存储（自动保存新字段：startDate/endDate）
const saveCoursesToLocalStorage = () => {
  console.log('准备保存到本地存储的课程：', courses.value); // 新增：保存前打印
  localStorage.setItem('scu_courses', JSON.stringify(courses.value))
}

// 4. 课程冲突检测（支持 日期 + 星期 + 时间 对比）
const checkCourseConflict = (newCourse, existingCourses) => {
  const convertDateToTimestamp = (dateStr) => new Date(dateStr).getTime()
  const convertTimeToTimestamp = (timeStr) => {
    const [hours, minutes] = timeStr.split(':').map(Number)
    return hours * 60 + minutes
  }

  for (const course of existingCourses) {
    // 步骤1：日期范围是否重叠
    const newStartDate = convertDateToTimestamp(newCourse.startDate)
    const newEndDate = convertDateToTimestamp(newCourse.endDate)
    const existStartDate = convertDateToTimestamp(course.startDate)
    const existEndDate = convertDateToTimestamp(course.endDate)
    const isDateOverlap = !(newEndDate < existStartDate || newStartDate > existEndDate)
    if (!isDateOverlap) continue

    // 步骤2：是否为同一天（星期）
    if (String(course.day) !== String(newCourse.day)) continue

    // 步骤3：时间段是否重叠
    const newStartTime = convertTimeToTimestamp(newCourse.startTime)
    const newEndTime = convertTimeToTimestamp(newCourse.endTime)
    const existStartTime = convertTimeToTimestamp(course.startTime)
    const existEndTime = convertTimeToTimestamp(course.endTime)
    const isTimeOverlap = newStartTime < existEndTime && newEndTime > existStartTime

    if (isTimeOverlap) {
      return { hasConflict: true, conflictCourse: course }
    }
  }
  return { hasConflict: false, conflictCourse: null }
}

// 5. 重新检测所有课程的冲突（编辑/删除后）
const checkAllCoursesConflict = () => {
  courses.value.forEach(course => {
    course.isConflict = false
  })
  for (let i = 0; i < courses.value.length; i++) {
    for (let j = i + 1; j < courses.value.length; j++) {
      const { hasConflict } = checkCourseConflict(courses.value[i], [courses.value[j]])
      if (hasConflict) {
        courses.value[i].isConflict = true
        courses.value[j].isConflict = true
      }
    }
  }
  saveCoursesToLocalStorage()
}

// 6. 课程提交（添加/编辑，自动处理日期字段）
const handleCourseSubmit = (course) => {
  console.log('接收到的课程数据：', course)
  const courseWithId = {
    id: course.id || Date.now().toString(),
    ...course,
    isConflict: false
  }

  if (!showEditForm.value) {
    // 用“展开运算符重新赋值”替代 push，强制触发响应式更新
    courses.value = [...courses.value, courseWithId]; 
    console.log('新 courses 数组：', courses.value);
    showAddForm.value = false;
    saveCoursesToLocalStorage();
  }

  // if (showEditForm) {
  //   const index = courses.value.findIndex(item => item.id === course.id)
  //   if (index !== -1) {
  //     courses.value.splice(index, 1, courseWithId)
  //     checkAllCoursesConflict()
  //   }
  //   showEditForm.value = false
  // } else {
  //   // const { hasConflict, conflictCourse: conflict } = checkCourseConflict(courseWithId, courses.value)
  //   // console.log('冲突检测结果：', hasConflict); // 新增：打印冲突检测结果
  //   // if (hasConflict) {
  //   //   showConflictAlert.value = true
  //   //   conflictCourse.value = conflict
  //   //   return
  //   // }
  //   courses.value.push(courseWithId)
  //   console.log('添加后 courses 数组：', courses.value); // 新增：push 后打印数组
  //   showAddForm.value = false

  //   nextTick(() => {
  //     console.log('nextTick 后 courses 数组：', courses.value);
  //     saveCoursesToLocalStorage();
  //   })
  // }
  //saveCoursesToLocalStorage()
}

// 7. 编辑课程：传递完整数据（含 startDate/endDate）
const handleEditCourse = (course) => {
  showEditForm.value = true
  currentEditCourse.value = { ...course }
}

// 8. 删除课程：删除后重新检测冲突
const handleDeleteCourse = (courseId) => {
  if (confirm('Are you sure you want to delete this course?')) {
    courses.value = courses.value.filter(course => course.id !== courseId)
    checkAllCoursesConflict()
    saveCoursesToLocalStorage()
  }
}

// 9. 取消表单：重置状态
const handleFormCancel = () => {
  showAddForm.value = false
  showEditForm.value = false
  currentEditCourse.value = null
}
</script>